using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Base;
using Model;
using FirebirdSql.Data.FirebirdClient;

namespace FirebirdTool
{
    public partial class FbSQL : DevExpress.XtraEditors.XtraUserControl
    {
        private string name = null;
        private string realName = null;
        private bool isModify = false;
        private List<Column> lstColumn = null;
        private Column colPK = null;
        private DataTable table = null;
        private bool flag = true;

        public FbSQL(string name, string realName, string content)
        {
            InitializeComponent();

            this.name = name;
            this.realName = realName;
            this.txtQuery.Text = content;

            this.isModify = false;

            this.KeyDown += new KeyEventHandler(FbSQL_KeyDown);
            this.txtQuery.KeyDown += new KeyEventHandler(FbSQL_KeyDown);
            this.txtMessage.KeyDown += new KeyEventHandler(FbSQL_KeyDown);

            this.btnRun.Click += new EventHandler(btnRun_Click);
        }

        public FbSQL(string tableName, string realTableName)
        {
            InitializeComponent();

            this.name = tableName;
            this.realName = realTableName;
            this.lblSQL.Text = "SELECT * FROM " + realTableName;
            this.lblSQL.Visible = true;

            this.isModify = true;
            this.lstColumn = Util.GetListColumn(realTableName);
            for (int i = 0; i < this.lstColumn.Count; i++)
                if (this.lstColumn[i].PK)
                {
                    colPK = this.lstColumn[i];
                    break;
                }

            this.KeyDown += new KeyEventHandler(FbSQL_KeyDown);
            this.txtQuery.KeyDown += new KeyEventHandler(FbSQL_KeyDown);
            this.txtMessage.KeyDown += new KeyEventHandler(FbSQL_KeyDown);

            this.gridControl.KeyDown += new KeyEventHandler(FbSQL_KeyDown);
            this.btnRun.Click += new EventHandler(btnRun_Click);

            RunQuery();
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            RunQuery();
        }

        private void FbSQL_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F5)
                RunQuery();
            else
                if (e.KeyCode == Keys.Delete)
                {
                    if (this.xtraTabControl1.SelectedTabPage == this.tabData)
                        Delete();
                }
        }

        private void RunQuery()
        {
            this.flag = false;
            this.txtMessage.Text = "";
            this.gridView.Columns.Clear();
            string scmd = "";

            if (this.isModify)
                scmd = this.lblSQL.Text + " " + this.txtQuery.Text;
            else
                scmd = this.txtQuery.Text;

            scmd = scmd.Trim();
            if (scmd.ToUpper().StartsWith("SELECT") == false)
            {
                try
                {
                    using (FbConnection cnn1 = new FbConnection(string.Format(Util.CnnStr, Util.DB)))
                    {
                        cnn1.Open();

                        using (FbCommand cmd1 = new FbCommand(scmd, cnn1))
                        {
                            int count = cmd1.ExecuteNonQuery();
                            this.txtMessage.Text = count + " rows effect";
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.txtMessage.Text = ex.Message;
                }

                this.xtraTabControl1.SelectedTabPage = this.tabMessage;
                return;
            }
            else
            {
                try
                {
                    using (FbConnection cnn = new FbConnection(string.Format(Util.CnnStr, Util.DB)))
                    {
                        cnn.Open();

                        using (FbCommand cmd = new FbCommand(scmd, cnn))
                        {
                            using (FbDataReader reader = cmd.ExecuteReader())
                            {
                                int i = 0;
                                int length = reader.FieldCount;

                                this.table = new DataTable();

                                for (i = 0; i < length; i++)
                                {
                                    DataColumn col = new DataColumn(reader.GetName(i), reader.GetFieldType(i));
                                    col.Caption = reader.GetName(i);
                                    this.table.Columns.Add(col);
                                }

                                while (reader.Read())
                                {
                                    object[] arrData = new object[length];
                                    arrData[0] = 0;
                                    for (i = 0; i < length; i++)
                                        arrData[i] = reader[i];

                                    this.table.Rows.Add(arrData);
                                }

                                this.gridControl.DataSource = this.table;
                                this.gridView.CheckLoaded();
                                this.gridView.BestFitColumns();

                                if (this.isModify)
                                {
                                    this.gridView.Columns[colPK.RealName].OptionsColumn.AllowEdit = false;
                                    this.gridView.Columns[colPK.RealName].AppearanceCell.ForeColor = Color.FromArgb(122, 122, 122);
                                }
                            }
                        }
                    }

                    this.xtraTabControl1.SelectedTabPage = this.tabData;
                }
                catch (Exception ex)
                {
                    this.txtMessage.Text = ex.Message;
                    this.xtraTabControl1.SelectedTabPage = this.tabMessage;
                    return;
                }
            }
            this.flag = true;
        }

        private void Delete()
        {
            if (XtraMessageBox.Show("Delete selected rows?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                int? ID = 0;
                int[] arrRow = this.gridView.GetSelectedRows();
                for (int i = 0; i < arrRow.Length; i++)
                {
                    if (arrRow[i] >= 0)
                    {
                        ID = StaticUtil.GetRealInt(this.gridView.GetRowCellValue(arrRow[i], colPK.RealName));

                        if (ID != null)
                            Util.ExecNonQuery("DELETE FROM " + this.realName + " WHERE " + colPK.RealName + "=" + ID.Value.ToString() + ";");
                    }
                }

                try
                {
                    this.gridView.DeleteSelectedRows();
                }
                catch { }
            }
        }
    }
}
